package gui.tree;

import java.util.Vector;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import record.Directory;
import record.ProjectRecord;

/**
 * A tree model that works with the GeoExplorer Directory class
 * 
 * @see record.Directory
 * @author Stephan
 *
 */
public class FileTreeModel implements TreeModel
{
	/**
	 * The listeners of this file tree model
	 */
    private Vector<TreeModelListener> treeModelListeners =
        new Vector<TreeModelListener>();

    /**
     * The root directory of this file tree
     */
	private Directory root;
	
	/**
	 * Initializes the file tree with the given root
	 * @param root the root of this file tree
	 */
	public FileTreeModel(Directory root)
	{
		this.root = root;
	}

	/**
	 * @see TreeModel#addTreeModelListener(TreeModelListener)
	 */
	@Override
	public void addTreeModelListener(TreeModelListener l)
	{
		treeModelListeners.add(l);
	}

	/**
	 * @see TreeModel#getChild(Object, int)
	 */
	@Override
	public Object getChild(Object parent, int index)
	{
		// bad index
		if(index < 0 || index > getChildCount(parent))
			//throw new IllegalArgumentException();
			return null;
		
		Directory dir = (Directory)parent;
		
		return dir.get(index);
	}

	/**
	 * @see TreeModel#getChildCount(Object)
	 */
	@Override
	public int getChildCount(Object parent)
	{
		// Projects have no children
		if(parent instanceof ProjectRecord)
			return 0;
		
		Directory dir = (Directory)parent;
		return dir.countContents();
	}

	/**
	 * @see TreeModel#getIndexOfChild(Object, Object)
	 */
	@Override
	public int getIndexOfChild(Object parent, Object child)
	{
		Directory dir = (Directory)parent;
		
		if(child instanceof Directory)
			return dir.indexOf((Directory)child);
		
		return dir.indexOf((ProjectRecord)child);
	}

	/**
	 * @see TreeModel#getRoot()
	 */
	@Override
	public Object getRoot()
	{
		return root;
	}

	/**
	 * @see TreeModel#isLeaf(Object)
	 */
	@Override
	public boolean isLeaf(Object node)
	{
		// only projects can be leaves
		return node instanceof ProjectRecord;
	}

	/**
	 * @see TreeModel#removeTreeModelListener(TreeModelListener)
	 */
	@Override
	public void removeTreeModelListener(TreeModelListener l)
	{
		treeModelListeners.remove(l);
	}
	
	/**
	 * @see TreeModel#valueForPathChanged(TreePath, Object)
	 */
	@Override
	public void valueForPathChanged(TreePath path, Object newValue)
	{
        System.out.println("*** valueForPathChanged : "
                + path + " --> " + newValue);
	}

}
